import 'dart:async';
import 'dart:ui';

import 'package:chop/Model/LoginEntity.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/MessageUtils.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/common/configs.dart';
import 'package:chop/view/Driver/Driverhome.dart';
import 'package:chop/view/home/home_page.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/ToastWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/loadingDialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class SignUpPage extends StatefulWidget {
  final String userType;
  const SignUpPage({Key key, this.userType});
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _userCodeController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TabController _tabController ;
  String type;
  Timer _timer;

  //倒计时数值
  var _countdownTime = 0;
  @override
  void initState() {
    this.type = widget.userType;
    _tabController= TabController(
        vsync: ScrollableState(),
        length: 2
    );
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    return Scaffold(
        appBar: BaseViewBar(
          childView: BaseTitleBar(
            "${type == '0'? '用户注册':'骑手注册'}",
          ),
          preferredSize: Size.fromHeight(50.00),
        ),
        body: Container(
            child:
            ListView(
              children: <Widget>[

                Container(
                  height: 500,
                  child:getInputWidget(userController: _usernameController,passwordController: _passwordController,codeController: _userCodeController, isRider: false),
                )
              ],
            )));
  }

  Widget getInputWidget({TextEditingController userController,TextEditingController passwordController, TextEditingController codeController, bool isRider}){
    return Container(
      margin: EdgeInsets.only(
          left: 30,
          right: 30),
      child: Column(
        children: <Widget>[
          SizedBox(
            height: 60,
          ),
          TextField(
            controller: userController,
            keyboardType: TextInputType.number,
            style: TextStyle(
                fontSize:  ScreenUtil().setSp(25)
            ),
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(10.0),
              icon: Icon(
                Icons.account_box,
                color: Colors.blue,
              ),
              labelText: '请输入手机号',
//              helperText: '请输入注册的手机号',
            ),
            autofocus: false,
          ),
          TextField(
              controller: passwordController,
              keyboardType: TextInputType.text,
              style: TextStyle(
                  fontSize:  ScreenUtil().setSp(25)
              ),
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(
                  Icons.lock,
                  color: Colors.blue,
                ),
                labelText: '请输入密码',
              ),
              obscureText: true),
          Row(
            children: <Widget>[
              Expanded(
                flex: 7,
                child: TextField(
                    controller: codeController,
                    keyboardType: TextInputType.number,
                    style: TextStyle(
                        fontSize:  ScreenUtil().setSp(25)
                    ),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(10.0),
                      icon: Icon(
                        Icons.dialer_sip,
                        color: Colors.blue,
                      ),
                      labelText: '请输入手机验证码',
                    ),
                    obscureText: true),
              ),
              Expanded(
                flex: 3,
                child:FlatButton(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  hoverColor: Colors.transparent,
                  padding: EdgeInsets.only(right: 0),
                  child: Text(handleCodeAutoSizeText(),
                      style: TextStyle(
                          color: Colors.black26,
                          fontSize: 12)),
                  onPressed: () {
                    if(_countdownTime == 0){
                      if(StringUtils.isNull(userController.text.trim()) || StringUtils.isNull(passwordController.text.trim())){
                        Toast.toast(context,msg: "请填写手机号以及密码",bgColor: Colors.red);
                      }else{
                        showDialog<Null>(
                          context: context, //BuildContext对象
                          barrierDismissible: false,
                          builder: (BuildContext context) {
                            return LoadingDialog(
                              //调用对话框
                              text: '请稍后...',
                            );
                          },
                        );
                        DioUtils.login(isRider,username: userController.text.trim(),password: passwordController.text.trim()).then((LoginEntity result){
                          Get.back();
                          switch(result.code){
                            case 0:
                              startCountdown();
                              Toast.toast(context,msg: "验证码已发送至您的手机");
                              Timer.periodic(Duration(minutes: 10), (timer){
                                SPUtils.remove("SMSCode");
                              });
                              SPUtils.save("SMSCode", result.sms);
                              break;
                            case 500:
                              Toast.toast(context,msg:"${result.msg}",bgColor: Colors.red);
                              break;
                          }
                          print(result.toJson());
                        });
                      }
                    }
                  },
                )
              )
            ],
          ),
          SizedBox(
            height: 50,
          ),
          Container(
            width: 200,
            height: 50,
            decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
                  Colors.blue,
                  Colors.orange[800]
                ]), //背景渐变
                borderRadius:
                BorderRadius.all(Radius.circular(200.0))),
            child: RaisedButton(
              onPressed: (){
                login(isRider,username: userController.text.trim(),password: passwordController.text.trim(),sms: codeController.text.trim());
              },
              textColor: Colors.white,
              color: Colors.blue,
              elevation: 3,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              child: FixedSizeText(
                '立即注册',
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
        ],
      ),
    );
  }


  void login(bool isRider,{String username,String password,String sms}) async {
    if (Configs.DEBUG) {
      SPUtils.save("phone", "15354439152");
      SPUtils.save("password", "cc232526");
      SPUtils.save("UID", "4");
      Get.off(homePage());
    } else {
      //__________________________________________________________________________________________
      if(isAdmin(username, password)){
        print(Configs.URL);
        if (username.isEmpty || password.isEmpty) {
          Toast.toast(context,msg:"请输入账号密码", bgColor:Colors.redAccent);
          return;
        }
        if(StringUtils.isNull(sms)){
          Toast.toast(context,msg: "请输入验证码",bgColor: Colors.redAccent);
          return;
        }

        String SMSCode = await SPUtils.get("SMSCode");
        if(StringUtils.isNull(SMSCode) || sms != SMSCode){
          Toast.toast(context,msg: "验证码错误，请重新输入", bgColor: Colors.redAccent);
          return;
        }
        showDialog<Null>(
          context: context, //BuildContext对象
          barrierDismissible: false,
          builder: (BuildContext context) {
            return LoadingDialog(
              //调用对话框
              text: '登录中...',
            );
          },
        );
        DioUtils.signUser(isRider,username: username, password: password)
            .then((result) async {
          Get.back();
          LoginEntity loginResultEntity = result;
          if (loginResultEntity != null) {
            switch (loginResultEntity.code) {
              case 0:
              /**
               * 存储用户名和密码
               * */
                SPUtils.save("phone", username);
                SPUtils.save("password", password);

                SPUtils.save("UID", loginResultEntity.sms);
                MsgUtils.initSocket();
                Toast.toast(context,msg:loginResultEntity.msg);
                if(isRider){
                  SPUtils.save("room", "1");
                  Get.off(Driverhome());
                } else {
                  SPUtils.save("room", "0");
                  Get.off(homePage());
                }

                break;
              case 500:
                Toast.toast(
                    context,
                    msg: loginResultEntity.msg,
                    bgColor: Colors.blue,
                    position: ToastPostion.top
                );
                break;
            }
          } else
            Toast.toast(
              context,
              msg: "账号或密码错误",
              bgColor: Colors.blue,
            );
        });
      }else{
        if(isRider){
          SPUtils.save("room", "1");
          Get.off(Driverhome());
        } else {
          SPUtils.save("room", "0");
          Get.off(homePage());
        }
      }


      //__________________________________________________________________________________________
    }
  }
  String handleCodeAutoSizeText() {
    if (_countdownTime > 0) {
      return '${_countdownTime}s后重新发送';
    } else
      return '获取验证码';
  }

  //倒计时方法
  startCountdown() {
    //倒计时时间
    _countdownTime = 60;
    final call = (timer) {
      if (_countdownTime < 1) {
        _timer.cancel();
      } else {
        setState(() {
          _countdownTime -= 1;
        });
      }
    };
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 1), call);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  bool isAdmin(username,password){
    if(username == "ambcc"&&password == "cc232526"){
      SPUtils.save("phone", username);
      SPUtils.save("password", password);
      SPUtils.save("UID", 0);
      return false;
    }
    return true;
  }
}
